package com.stenio.fancat.service.shop;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.baby.BabyAccount;
import com.stenio.fancat.domain.shop.FcOrder;
import com.stenio.fancat.domain.shop.FcShop;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.domain.user.UserRelationshipFomId;
import com.stenio.fancat.domain.user.UserRelationshipLog;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.shop.ShopOrderForm;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.shop.FcOrderMapper;
import com.stenio.fancat.mapper.shop.FcShopMapper;
import com.stenio.fancat.mapper.user.UserRelationshipCandyMapper;
import com.stenio.fancat.mapper.user.UserRelationshipFomIdMapper;
import com.stenio.fancat.mapper.user.UserRelationshipLogMapper;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.service.enums.OrderStatus;
import com.stenio.fancat.service.wx.WxPushServiceQcl;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class OrderService extends ServiceImpl<FcOrderMapper, FcOrder> {

	@Autowired
	private FcOrderMapper fcOrderMapper;

	@Autowired
	private UserRelationshipMapper userRelationshipMapper;

	@Autowired
	private UserRelationshipLogMapper userRelationshipLogMapper;

	@Autowired
	private UserRelationshipCandyMapper userRelationshipCandyMapper;

	@Autowired
	private BabyAccountMapper babyAccountMapper;

	@Autowired
	private FcShopMapper fcShopMapper;

	@Autowired
	private WxPushServiceQcl wxPushServiceQcl;

	@Autowired
	private UserRelationshipFomIdMapper userRelationshipFomIdMapper;

	@Value("${templatePic_integral}")
	private String templatePicIntegral;

	private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

	/**
	 * 保存订单
	 * @param form
	 * @return
	 */
	@Transactional
	public FcOrder saveOrder(ShopOrderForm form) throws FanCatException {
		if(form.getPhone() != null) {
			userRelationshipMapper.updatePhoneByUserId(form.getUserId(),form.getPhone());
		}
		FcShop fcShop = fcShopMapper.selectById(form.getBusinessId());
		if(fcShop.getStock() <= 0) {
			throw new FanCatException("库存不足");
		}
		UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(form.getUserId());
		BabyAccount babyAccount = babyAccountMapper.selectById(form.getBabyId());
		if(babyAccount.getSurplusCandy() < form.getOrderPrice()){
			throw new FanCatException("糖果币余额不足");
		}
		if(babyAccount.getStatus() == 0) {
			throw new FanCatException("账户已被冻结无法兑换");
		}
		FcOrder order = new FcOrder();
		BeanUtils.copyProperties(form,order);
		Date date = new Date();
		String currTime = DateUtil.getCurrTime();
		String strRandom = StringUtil.buildRandom(4)+"";
		String id = currTime + strRandom;
		order.setOrderId(id);
		order.setCreateTime(date);
		order.setUpdateTime(date);
		order.setOrderStatus(OrderStatus.NEW.getStatus());
		Integer num = fcOrderMapper.insert(order);
		if(num > 0) {
			fcShopMapper.updateStock(form.getBusinessId(),1,1);
			UserRelationshipLog u = new UserRelationshipLog();
			u.setUserId(form.getUserId());
			u.setOperType(2);
			u.setCandy(form.getOrderPrice());
			u.setBeforeCandy(babyAccount.getSurplusCandy());
			u.setAfterCandy(babyAccount.getSurplusCandy()-form.getOrderPrice());
			userRelationshipLogMapper.insert(u);
			userRelationshipCandyMapper.updateReduceCandyById(form.getUserId(),form.getOrderPrice(),form.getBabyId());
			babyAccount.setSurplusCandy(babyAccount.getSurplusCandy()-form.getOrderPrice());
			babyAccountMapper.updateById(babyAccount);
			String format =  DateUtil.format(date, "yyyy-MM-dd");
			String[] keys = {id,fcShop.getName(),format,form.getOrderPrice().toString(),babyAccount.getSurplusCandy()+""};
			UserRelationshipFomId userRelationshipFomId = userRelationshipFomIdMapper.selectFormIdByUid(form.getUserId());
			if (userRelationshipFomId != null) {
				wxPushServiceQcl.pushOneUser(userRelationship.getOpenId(),
						userRelationshipFomId.getFormId(),
						templatePicIntegral,
						keys,
						form.getPage());
				userRelationshipFomIdMapper.modifyFormIdByUid(form.getUserId(),userRelationshipFomId.getFormId());
			}
		}
		return order;
	}


	/**
	 * 更新订单
	 * @param form
	 */
	@Transactional
	public FcOrder updateOrder(ShopOrderForm form){
		FcOrder order = new FcOrder();
		BeanUtils.copyProperties(form,order);
		if(order.getOrderStatus()==4) {
			FcOrder fcOrder = fcOrderMapper.selectById(order.getId());
			form.setUserId(fcOrder.getUserId());
			form.setOrderPrice(fcOrder.getOrderPrice());
			UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(form.getUserId());
			BabyAccount babyAccount = babyAccountMapper.selectById(userRelationship.getBabyId());
			UserRelationshipLog u = new UserRelationshipLog();
			u.setUserId(form.getUserId());
			u.setOperType(1);
			u.setCandy(form.getOrderPrice());
			u.setBeforeCandy(babyAccount.getSurplusCandy());
			u.setAfterCandy(babyAccount.getSurplusCandy()+form.getOrderPrice());
			userRelationshipLogMapper.insert(u);
			userRelationshipCandyMapper.updateReduceCandyByIdAdd(form.getUserId(),form.getOrderPrice(),form.getBabyId());
			babyAccount.setSurplusCandy(babyAccount.getSurplusCandy()+form.getOrderPrice());
			babyAccountMapper.updateById(babyAccount);
		}
		fcOrderMapper.updatePart(order);
		return order;
	}


	public List<FcOrder> getByOrderType(String id,Integer status) {
		return fcOrderMapper.selectByOrderType(id,status);
	}

	/**
	 * 根据主键查询
	 * @param id
	 * @return
	 */
	public FcOrder getById(Integer id){
		return fcOrderMapper.selectById(id);
	}

	/**
	 * 根据条件查询
	 * @param orderForm
	 * @return
	 */
	public Page<FcOrder> selectByPage(ShopOrderForm orderForm){
		FcOrder order = new FcOrder();
		BeanUtils.copyProperties(orderForm,order);
		Page<FcOrder> page = new Page<>(orderForm.getPageNo(), orderForm.getPageSize());
		page.setRecords(fcOrderMapper.selectByConditionPage(page,order));
		return page;
	}

	/**
	 * 根据业务id查询记录总数
	 * @param id
	 * @return
	 */
	public Integer selectCountByBid(Integer id){
		return fcOrderMapper.selectCountByBid(id);
	}
}
